package com.google.code.dweibo.core.auth;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.google.code.dweibo.util.WeiboTokenException;

import weibo4j.Oauth;
import weibo4j.Weibo;
import weibo4j.http.AccessToken;
import weibo4j.model.WeiboException;
import weibo4j.util.BareBonesBrowserLaunch;


public class SinaLoginService extends LoginService{
	
	public SinaLoginService(){
		setWeiboAccessToken(new SinaWeiboAccessToken());
	}
	
	class SinaWeiboAccessToken implements WeiboAccessToken{
		private Oauth oauth;
		public SinaWeiboAccessToken(){
			oauth = new Oauth();
		}
		@Override
		public String getAccessToken(String pinCode) throws WeiboTokenException {
			AccessToken token = null;
			try {
				token = oauth.getAccessTokenByCode(pinCode);
			} catch (WeiboException e) {
				// TODO Auto-generated catch block
				throw new WeiboTokenException(e.getMessage());
			}
			// TODO Auto-generated method stub
			return token.getAccessToken();
		}
		@Override
		public String getAuthorizeCode() throws WeiboTokenException {
			// TODO Auto-generated method stub
			try {
				return oauth.authorize("code");
			} catch (WeiboException e) {
				// TODO Auto-generated catch block
				throw new WeiboTokenException(e.getMessage());
			}
		}
		
	}
	
	@Override
	public String getPinCode() throws Exception {
		// TODO Auto-generated method stub
		BufferedReader br = null;
		try {
			BareBonesBrowserLaunch.openURL(this.getWeiboAccessToken().getAuthorizeCode());
			System.out.print("Hit enter when it's done.[Enter]:");
			br = new BufferedReader(new InputStreamReader(System.in));
			return br.readLine();
		} finally{
			if(br!=null)
				br.close();
		}
		
	}

	@Override
	public void initializeToken(String token) {
		// TODO Auto-generated method stub
		Weibo.client.setToken(token);
	}

}
